<template>
<div class="img-upload">
  <el-upload
    :action="$url.uploadURL"
    :name="name"
    :file-list="list"
    :on-success="imgUpdated"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <template #tip>
      <slot name="tip" />
    </template>
  </el-upload>
</div>
</template>

<script>
export default {
  name: 'ImgUpload',
  props: {
    name: { type: String, require: true, default: '' },
    // 用于v-model进行双向绑定传递的值是
    value: { type: String, require: false, default: '' }
  },

  data() {
    return {
      // file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
      // 图片上传重点是使url绑定相关的图片地址
      fileList: []
    }
  },

  computed: {
    list() {
      return this.fileList.length > 0 ? this.fileList : (this.value ? [{ name: '', url: this.$url.imgServe + this.value }] : [])
    }
  },

  methods: {
    // 图片上传，图片上传后成功回调
    imgUpdated (res) {
      if (res && res.data && res.data.img) {
        this.$emit('input', res.data.img)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>